<template>
    <div>
        <el-row>
            <el-col :span="18" :offset="3">
                <recommend-post-card
                    link
                    @changeLabelAttention="changeLabelAttention"
                    :postList="postList"
                    v-if="getUser"></recommend-post-card>
                <div v-for="areaPost in areaPosts"
                     :key="areaPost.area.id">
                    <area-post-card
                        link
                        @changeLabelAttention="changeLabelAttention"
                        :areaPost="areaPost"></area-post-card>
                </div>
            </el-col>
        </el-row>
    </div>
</template>

<script>
    import { mapGetters, mapActions } from 'vuex'
    import RecommendPostCard from './recommendPostCard'
    import AreaPostCard from './areaPostCard'

    export default {
        name: 'home',
        components: {
            RecommendPostCard,
            AreaPostCard
        },
        data () {
            return {
                areas: [],
                postList: [],
                areaPosts: []
            }
        },
        mounted () {
            if (this.getUser) {
                this.action(this.recommendAction(), data => {
                    this.postList = data.data.slice(0, 8)
                })
            }
            this.action(this.pageAreaAction({ page: 1, size: 5 }), data => {
                    let areas = data.data.records
                    this.areas = areas.filter(area => area.name !== 'root')
                    this.areas.forEach(area => {
                        this.action(this.pageAreaPostAction({ area: area.name, page: 1, size: 8 }), data => {
                            this.areaPosts.push({ area: area, posts: data.data.records })
                        })
                    })
                }
            )
        },
        computed: {
            ...mapGetters('user', [
                'getUser'
            ])
        },
        methods: {
            ...mapActions({
                pageAreaAction: 'area/pageArea',
                recommendAction: 'post/recommend',
                pageAreaPostAction: 'post/pageAreaPost'
            }),
            changeLabelAttention (data) {
                this.postList.forEach(post => {
                    post.labels.forEach(label => {
                        if (label.id === data.id) {
                            label.attentionCount += data.inc
                        }
                    })
                })
                this.areaPosts.forEach(areaPost => {
                    areaPost.posts.forEach(post => {
                        post.labels.forEach(label => {
                            if (label.id === data.id) {
                                label.attentionCount += data.inc
                            }
                        })
                    })
                })
            }
        }
    }
</script>

<style scoped>

</style>
